package com.info33.platform.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.info33.platform.common.exception.TransactionalException;
import com.info33.platform.common.mvc.vo.Result;
import com.info33.platform.system.dao.SysAppMenuDao;
import com.info33.platform.system.dao.SysAppTenantMenuDao;
import com.info33.platform.system.entity.SysAppMenu;
import com.info33.platform.system.entity.SysAppTenantMenu;
import com.info33.platform.system.service.SysAppMenuService;
import com.info33.platform.system.vo.SysAppMenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author admin
 */
@Service
public class SysAppMenuServiceImpl extends ServiceImpl<SysAppMenuDao, SysAppMenu> implements SysAppMenuService {

    @Autowired
    private SysAppMenuDao sysAppMenuDao;
    @Autowired
    private SysAppTenantMenuDao sysAppTenantMenuDao;

    @Override
    public Result<Object> pcDelete(Long mid) {
        Integer count = sysAppTenantMenuDao.selectCount(new QueryWrapper<SysAppTenantMenu>().eq("menu_id", mid));
        if (count > 0) {
            return Result.error("已有 " + count + " 个租户，已分配此菜单，不可删除");
        }
        return sysAppMenuDao.deleteById(mid) == 1 ? Result.ok() : Result.error();
    }

    @Override
    public List<SysAppMenuVO> pcTree() {
        List<SysAppMenuVO> appMenus = sysAppMenuDao.getAll();
        List<SysAppMenuVO> collect = appMenus.stream().filter(l -> l.getPid().equals(1L)).collect(Collectors.toList());
        collect.forEach(l -> l.setSons(appMenus.stream().filter(ll -> ll.getPid().equals(l.getId())).collect(Collectors.toList())));
        return collect;
    }

    @Override
    public Result<Object> pcAdd(SysAppMenu appMenu) {
        if (!this.save(appMenu)) {
            return Result.error(Result.RESULT_ERROR_PUBLIC_MSG);
        }
        // 默认添加到当前租户下
        SysAppTenantMenu atm = new SysAppTenantMenu();
        atm.setMenuId(appMenu.getId());
        atm.setRemarks(appMenu.getRemarks());
        if (sysAppTenantMenuDao.insert(atm) != 1) {
            throw new TransactionalException();
        }
        return Result.ok();
    }
}